package com.yokead.controller.sysadmin.domain;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharsetUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;
import com.yokead.common.UserUtil;
import com.yokead.common.base.RewriteBaseControl;
import com.yokead.common.tools.UrlPath;
import com.yokead.service.domain.DoMainServer;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by jiangzeyin on 2017/8/7.
 */
@Controller
@RequestMapping("sysadmin")
public class DoMainController extends RewriteBaseControl {
    @Resource
    private DoMainServer doMainServer;


    @RequestMapping(value = "domain.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String doMain() {
        try {
            JSONObject jsonObject = doMainServer.getUrls();
            JSONObject default_ = jsonObject.getJSONObject("default");
            if (default_ != null) {
                setAttribute("company", default_.getJSONArray("company"));
                setAttribute("personal", default_.getJSONArray("personal"));
            }
            setAttribute("customer", jsonObject.getJSONObject("customer"));
            setAttribute("customer_diy", getCustomer_Diy());
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名列表错误", e);
        }
        return "sysadmin/domain/domain";
    }

    /**
     * 获取客户域名
     *
     * @return json
     * @throws IOException io
     */
    private JSONArray getCustomer_Diy() throws IOException {
        JSONObject jsonObject = doMainServer.getUrls();
        JSONObject customer_diy = jsonObject.getJSONObject(KhDoMainConfControl.KEY);
        if (customer_diy == null) {
            return null;
        }
        JSONArray jsonArray_all = new JSONArray();
        JSONArray doMain = UrlPath.start(Config.Nginx.getNginxConfigPath(), UrlPath.Type.DoMain);
        for (String key : customer_diy.keySet()) {
            JSONArray jsonArray_diy = customer_diy.getJSONArray(key);
            if (doMain != null) {
                jsonArray_diy.forEach(o -> {
                    JSONObject item_r = new JSONObject();
                    String doMainUrl = (String) o;
                    item_r.put("url", doMainUrl);
                    item_r.put("name", key);
                    item_r.put("need", true);
                    doMain.forEach(o1 -> {
                        JSONObject jsonObject1 = (JSONObject) o1;
                        String url = jsonObject1.getString("url");
                        if (doMainUrl.equals(url)) {
                            item_r.put("need", false);
                        }
                    });
                    jsonArray_all.add(item_r);
                });
            }
        }
        if (jsonArray_all.isEmpty()) {
            return null;
        }
        return jsonArray_all;
    }

    @RequestMapping(value = "get_child.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_child(String name) {
        try {
            JSONArray jsonArray = doMainServer.getDomainRList(name);
            if (jsonArray == null) {
                return JsonMessage.getString(400, "域名信息错误");
            }
            JSONArray doMain = UrlPath.start(Config.Nginx.getNginxConfigPath(), UrlPath.Type.DoMain);
            if (doMain != null) {
                jsonArray.forEach(o -> {
                    JSONObject jsonObject = (JSONObject) o;
                    String urlName = jsonObject.getString("name");
                    if ("@".equals(urlName)) {
                        return;
                    }
                    urlName = String.format("%s.%s", urlName, name);
                    String finalUrlName = urlName;
                    doMain.forEach(o1 -> {
                        JSONObject jsonObject1 = (JSONObject) o1;
                        String url = jsonObject1.getString("url");
                        if (!finalUrlName.equals(url)) {
                            return;
                        }
                        jsonObject.put("need", true);
                    });
                });
            }
            return JsonMessage.getString(200, "", jsonArray);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("域名处理错误", e);
            return JsonMessage.getString(500, "域名信息获取错误，请联系管理员");
        }
    }

    @RequestMapping(value = "domain_conf.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String domain_conf(String prefix, String doMain) {
        return "sysadmin/domain/domain_conf";
    }

    /**
     * 保存配置
     *
     * @param name   所属人员
     * @param tag    标记
     * @param domain 域名
     * @param prefix 前缀
     * @return 结果
     */
    @RequestMapping(value = "save_domain_conf.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_child(String name, String tag, String domain, String prefix) throws IOException {
        prefix = StringUtil.convertNULL(prefix);
        domain = StringUtil.convertNULL(domain);
        tag = convertFilePath(tag);
        if (StringUtil.isEmpty(tag)) {
            return JsonMessage.getString(100, "请输入目录标记");
        }
        boolean find = false;
        String doMainUrl;
        if (!"*".equals(prefix)) {
            // 验证dnspod
            doMainUrl = String.format("%s.%s", prefix, domain);
            JSONArray jsonArray;
            try {
                jsonArray = doMainServer.getDomainRList(domain);
            } catch (Exception e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名异常", e);
                return JsonMessage.getString(500, "处理异常");
            }
            if (jsonArray == null) {
                return JsonMessage.getString(400, "域名信息错误");
            }
            for (Object aJsonArray : jsonArray) {
                JSONObject jsonObject = (JSONObject) aJsonArray;
                String urlName = jsonObject.getString("name");
                if ("@".equals(urlName)) {
                    continue;
                }
                urlName = String.format("%s.%s", urlName, domain);
                if (doMainUrl.equals(urlName)) {
                    find = true;
                    break;
                }
            }
            if (!find) {
                return JsonMessage.getString(400, "没有对应域名");
            }
            prefix = tag;
            if ("*".equals(prefix)) {
                prefix = doMainUrl.replace(".", "-");
            }
        } else {
            // 判断客户链接
            JSONArray jsonArray;
            try {
                jsonArray = getCustomer_Diy();
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("读取错误", e);
                return JsonMessage.getString(500, "处理异常:-100");
            }
            if (jsonArray == null) {
                return JsonMessage.getString(400, "没有客户数据");
            }
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject) object;
                String url = jsonObject.getString("url");
                if (url.equals(domain)) {
                    find = true;
                    break;
                }
            }
            if (!find) {
                return JsonMessage.getString(400, "没有对应客户域名");
            }
            doMainUrl = domain;
        }
        // 验证是否配置
        try {
            JSONArray doMain = UrlPath.start(Config.Nginx.getNginxConfigPath(), UrlPath.Type.DoMain);
            Iterator<Object> iterator1 = doMain.iterator();
            find = false;
            while (iterator1.hasNext()) {
                JSONObject jsonObject1 = (JSONObject) iterator1.next();
                String url = jsonObject1.getString("url");
                if (doMainUrl.equals(url)) {
                    find = true;
                    break;
                }
            }
            if (find) {
                return JsonMessage.getString(400, "该域名异常配置过了");
            }
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("获取域名异常", e);
            return JsonMessage.getString(500, "处理异常:-1");
        }
        //
        if (!domain.contains(".")) {
            return JsonMessage.getString(500, "域名：" + domain + " 错误");
        }
        String pathDomain = domain.substring(0, domain.indexOf("."));
        if (!UserUtil.check(name)) {
            return JsonMessage.getString(500, "所属人员不正确");
        }
        if ("*".equals(prefix)) {
            prefix = doMainUrl.replace(".", "-");
        }
        // 验证conf 是否存在
        File confFile = new File(String.format("%s/%s/%s.conf", Config.Nginx.getNginxConfigPath(), name, prefix));
        if (confFile.exists()) {
            return JsonMessage.getString(100, "已经存在配置信息:" + prefix);
        }
        String rootPath = StringUtil.clearPath(String.format("%s/%s/%s/%s/", Config.Nginx.getStaticPath(), pathDomain, name, tag));
        File rootPathFile = new File(rootPath);
        if (rootPathFile.exists()) {
            return JsonMessage.getString(500, "对应目录已经存在");
        }
        // new File(getBootPath(), "nginx_default.conf");
        File nginx_default = Config.Nginx.getNginxDefaultConfigTemplateFile();
        String default_str;
        try {
            default_str = FileUtil.readString(nginx_default, CharsetUtil.CHARSET_UTF_8);
        } catch (IORuntimeException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("读取配置异常", e);
            return JsonMessage.getString(500, "读取配置异常");
        }
        // 判断log 文件是否存在
        ///var/log/nginx/log
        File logFile = new File(String.format("%s/%s/%s.log", Config.Nginx.getLogPath(), pathDomain, prefix));
        if (logFile.exists()) {
            return JsonMessage.getString(500, "日志文件以及存在");
        }
        // new File(String.format("/var/log/nginx/log/%s/", pathDomain));
        File logPath = logFile.getParentFile();
        if (!logPath.exists() && !logPath.mkdirs()) {
            //System.out.println("创建成功：" + logPath.getPath());
            return JsonMessage.getString(500, "日志目录创建失败");
        }
        default_str = StringUtil.convertNULL(default_str);
        default_str = default_str.replace("![domain]", doMainUrl);
        default_str = default_str.replace("![root]", rootPath);
        default_str = default_str.replace("![logPath]", pathDomain);
        default_str = default_str.replace("![logName]", prefix);
        // 写入配置信息
        try {
            FileUtil.writeString(default_str, confFile, CharsetUtil.CHARSET_UTF_8);
        } catch (IORuntimeException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存文件异常", e);
            return JsonMessage.getString(100, "保存文件异常");
        }
        if (new File(rootPathFile, "temp").mkdirs()) {
            reloadNginx(userName + "  add " + confFile.getPath());
            return JsonMessage.getString(200, "ok");
        }
        return JsonMessage.getString(100, "目录创建失败");
    }
}
